package br.unifor.mia.sd.proxy;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.net.ServerSocketFactory;

/**
 * <p>
 * Proxy class responsible for handling incoming Http requests and delegating
 * them to the correct target
 * </p>
 * 
 * @author Michel Vasconcelos
 * 
 */
public class HttpProxy {

	/** Receiving socket */
	ServerSocket server = null;

	Logger log = Logger.getLogger("br.unifor.mia.sd.proxy");

	int port = 0;

	public HttpProxy() {
		this(Integer.valueOf(ProxyConfiguration.getConfiguration().getProperty(
				ProxyConfiguration.DEFAULT_PORT)));
	}

	public HttpProxy(int port) {
		this.port = port;
		try {
			server = ServerSocketFactory.getDefault().createServerSocket(port);
		} catch (IOException e) {
			if (log.isLoggable(Level.SEVERE)) {
				log.log(Level.SEVERE, "Severe fault while opening the Socket.",
						e);
			}
		}
		if (log.isLoggable(Level.FINE)) {
			log.log(Level.FINE, " Proxy instantiated in port "
					+ server.getLocalPort() + ".\n");
		}
	}

	public void startUp() {
		while (true) {
			IncomingRequestHandler handler = null;
			try {
				if (log.isLoggable(Level.FINEST)) {
					log.log(Level.FINEST, "Proxy started.");
				}
				handler = new IncomingRequestHandler(server.accept());
				(new Thread(handler)).start();
			} catch (IOException ioe) {
				if (log.isLoggable(Level.SEVERE)) {
					log.log(Level.SEVERE, "Could not accept Connections.", ioe);
				}
			} catch (Exception e) {
				if (log.isLoggable(Level.SEVERE)) {
					log.log(Level.SEVERE, "Could not Start Proxy", e);
				}
			}
		}
	}
}
